package edu.tum.cs.i1.pse;

import javax.crypto.*;

import org.apache.commons.codec.binary.Base64;

import static javax.crypto.Cipher.DECRYPT_MODE;
import static javax.crypto.Cipher.ENCRYPT_MODE;

public class Blowfish implements Cipher {
	
	private SecretKey secretkey;
	private javax.crypto.Cipher blowfishCipher;
	
	public Blowfish() {
		try {
			KeyGenerator keygenerator = KeyGenerator.getInstance("Blowfish");
			secretkey = keygenerator.generateKey();
			blowfishCipher = javax.crypto.Cipher.getInstance("Blowfish");
		}
		catch (Exception e) {}
		
	}
	
	@Override
	public String encryptWord(String w, byte k) {
		byte[] resultArray;
		String result = null;
		try {
			blowfishCipher.init(ENCRYPT_MODE, secretkey);
			resultArray = blowfishCipher.doFinal(w.getBytes());
			result = Base64.encodeBase64String(resultArray);
		}
		catch (Exception e) {}
		
		return result;
	}

	@Override
	public String decryptWord(String w, byte k) {
		byte[] resultArray;
		byte[] wBase64;
		String result = null;
		try {
			wBase64 = Base64.decodeBase64(w);
			blowfishCipher.init(DECRYPT_MODE, secretkey);
			resultArray = blowfishCipher.doFinal(wBase64);
			result = new String(resultArray);
		}
		catch (Exception e) {}
		
		return result;
	}

}
